import axios from 'axios';
import cookies from './cookies';

import { Message } from "element-ui";


const service = axios.create({
    baseURL: window.SET_APIBASEURL,
    timeout: window.SET_APITIMEOUT
})
// 请求拦截
service.interceptors.request.use(config => {
    const token = cookies.get('token');
    if (token) {
        // 在请求发送之前做一些处理
        config.headers['token'] = token;
        config.headers['Authorization'] = 'Bearer ' + token;
        // 添加headers
        //config.headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    }
    return config
}, err => {
    return Promise.error(err);
})

// 响应拦截
service.interceptors.response.use(res => {
    return res.data
}, err => {
    Message.error(err.response.data.msg)
    return Promise.reject(err);
})

/**
 * $get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const $get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        service({
            method: "GET",
            url: url,
            ...params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    })
}

/**
 * $post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const $post = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        service({
            method: "POST",
            url: url,
            ...params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    })
}

/**
 * $delete方法，对应delete请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const $delete = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        service({
            method: "DELETE",
            url: url,
            ...params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    })
}

/**
 * $put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const $put = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        service({
            method: "PUT",
            url: url,
            ...params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    })
}

export default { $get, $post, $put, $delete }